package com.wispx.gateway.core.filter.route;

import com.wispx.gateway.core.context.GatewayContext;
import com.wispx.gateway.core.filter.Filter;
import com.wispx.gateway.core.helper.GatewayContextHelper;
import com.wispx.gateway.core.response.GatewayResponse;
import org.asynchttpclient.Response;

import java.util.concurrent.CompletableFuture;

import static com.wispx.gateway.common.constant.FilterConstant.ROUTE_FILTER_NAME;
import static com.wispx.gateway.common.constant.FilterConstant.ROUTE_FILTER_ORDER;

public class RouteFilter implements Filter {
    // 请求转发给下游
    @Override
    public void doPreFilter(GatewayContext ctx) {
        CompletableFuture<Response> future = RouteUtil.buildRouteSupplier(ctx).get().toCompletableFuture();
        future.exceptionally((throwable -> {
            ctx.setResponse(new GatewayResponse());
            GatewayContextHelper.writeBack2Client(ctx);
            return null;
        }));
    }

    @Override
    public void doPostFilter(GatewayContext ctx) {
        ctx.doFilter();
    }

    @Override
    public String mark() {
        return ROUTE_FILTER_NAME;
    }

    @Override
    public int getOrder() {
        return ROUTE_FILTER_ORDER;
    }
}
